<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>景区信息管理</title>
  <!--引入的vue.js-->
  <script src="/js/vue.js"></script>
  <!--引入elementUI的css-->
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <!--引入elementUI的js-->
  <script src="/js/index.js"></script>
  <!--引入axios.js-->
  <script src="/js/axios.min.js"></script>

  <style>
    .search-container {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
    .form-section {
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 20px;
      padding-bottom: 15px;
    }
    .form-section-title {
      font-weight: bold;
      color: #409EFF;
      margin-bottom: 15px;
      font-size: 16px;
    }
    .table-container {
      margin-top: 20px;
    }
    .action-buttons {
      display: flex;
      gap: 5px;
    }
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
    .dialog-footer {
      text-align: right;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .scenic-image {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }
    .status-pending {
      color: #909399;
      font-weight: bold;
    }
    .status-passed {
      color: #67C23A;
      font-weight: bold;
    }
    .status-rejected {
      color: #F56C6C;
      font-weight: bold;
    }
  </style>
</head>
<body>
<div id="app">
  <!-- 搜索框 -->
  <div class="search-container">
    <el-row :gutter="10">
      <el-col :span="4">
        <el-input v-model="searchForm.scenicCode" placeholder="请输入景区代码" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-input v-model="searchForm.scenicName" placeholder="请输入景区名称" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-input v-model="searchForm.jbcode" placeholder="请输入景区级别" clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-select
                v-model="searchForm.auditStatus"
                placeholder="请选择审核状态"
                style="width: 100%;">
          <el-option label="全部" value=""></el-option>
          <el-option label="审核中" value="0"></el-option>
          <el-option label="审核通过" value="1"></el-option>
          <el-option label="审核未通过" value="2"></el-option>
        </el-select>
      </el-col>

      <el-col :span="6">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加景区</el-button>
      </el-col>
<!--      <el-col :span="4">-->

<!--      </el-col>-->
<!--      <el-col :span="4"></el-col>-->
    </el-row>
  </div>

  <!-- 列表数据 -->
  <div class="table-container">
    <el-table :data="tableData" style="width: 100%" v-loading="loading" stripe>
      <el-table-column prop="scenicId" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="scenicCode" label="景区代码" width="120" align="center"></el-table-column>
      <el-table-column prop="scenicName" label="景区名称" width="150" align="center"></el-table-column>
      <!-- 修复：添加封面图片渲染模板 -->
      <el-table-column prop="scover" label="封面" width="100" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.scover"
               :src="scope.row.scover"
               class="scenic-image"
               @error="$event.target.src='/img/默认.jpg'">
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="jbcode" label="景区级别" width="100" align="center"></el-table-column>
      <el-table-column prop="yytime" label="营业时间" width="120" align="center"></el-table-column>
      <el-table-column prop="weight" label="推荐度" width="80" align="center"></el-table-column>

      <el-table-column prop="auditStatus" label="审核状态" width="120" align="center">
        <template slot-scope="scope">
                    <span :class="{
                        'status-pending': scope.row.auditStatus === '0',
                        'status-passed': scope.row.auditStatus === '1',
                        'status-rejected': scope.row.auditStatus === '2'
                    }">
                        {{ statusMap[scope.row.auditStatus] }}
                    </span>
        </template>
      </el-table-column>
      <!-- 当审核状态为2时，显示拒绝原因 -->
      <!-- 新增拒绝原因列 -->
      <el-table-column prop="rejectReason" label="拒绝原因" width="120" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.auditStatus === '2'">
            {{ scope.row.rejectReason || '无' }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" fixed="right">
        <template slot-scope="scope">
          <div class="action-buttons">
            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 添加/更新景区弹窗 -->
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="800px" :before-close="handleDialogClose">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px" style="max-height: 60vh; overflow-y: auto;">
      <div class="form-section">
        <div class="form-section-title">基础信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="景区代码" prop="scenicCode">
              <el-input v-model="form.scenicCode" autocomplete="off" :disabled="title==='更新景区'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="景区名称" prop="scenicName">
              <el-input v-model="form.scenicName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="封面" prop="scover">
              <el-input v-model="form.scover" autocomplete="off" placeholder="输入图片URL或点击上传"></el-input>
            </el-form-item>
          </el-col>
          <!-- 修复：添加图片上传组件 -->
          <el-col :span="12">
            <el-upload
                    class="avatar-uploader"
                    action="/scenic/uploadImage"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload">
              <img v-if="form.scover" :src="form.scover" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="景区级别" prop="jbcode">
              <el-select v-model="form.jbcode" placeholder="请选择景区级别" style="width: 100%;">
                <el-option label="A级" value="A"></el-option>
                <el-option label="AA级" value="AA"></el-option>
                <el-option label="AAA级" value="AAA"></el-option>
                <el-option label="AAAA级" value="AAAA"></el-option>
                <el-option label="AAAAA级" value="AAAAA"></el-option>
                <el-option label="未评级" value="未评级"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <div class="form-section-title">分类信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主题" prop="season">
              <el-select v-model="form.themecode" placeholder="请选择主题">
                <el-option label="自然风景" value="自然风景"></el-option>
                <el-option label="人文历史" value="人文历史"></el-option>
                <el-option label="主题公园" value="主题公园"></el-option>
                <el-option label="红色旅游" value="红色旅游"></el-option>
                <el-option label="乡村旅游" value="乡村旅游"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时令" prop="season">
              <el-select v-model="form.season" placeholder="请选择季节">
                <el-option label="春季" value="春季"></el-option>
                <el-option label="夏季" value="夏季"></el-option>
                <el-option label="秋季" value="秋季"></el-option>
                <el-option label="冬季" value="冬季"></el-option>
                <el-option label="春夏季" value="春夏季"></el-option>
                <el-option label="春秋季" value="春秋季"></el-option>
                <el-option label="春冬季" value="春冬季"></el-option>
                <el-option label="夏秋季" value="夏秋季"></el-option>
                <el-option label="夏冬季" value="夏冬季"></el-option>
                <el-option label="秋冬季" value="秋冬季"></el-option>
                <el-option label="春秋夏季" value="春秋夏季"></el-option>
                <el-option label="夏秋冬季" value="夏秋冬季"></el-option>
                <el-option label="春夏冬季" value="春夏冬季"></el-option>
                <el-option label="春秋冬季" value="春秋冬季"></el-option>
                <el-option label="四季" value="四季"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <div class="form-section-title">联系方式</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="景区地址" prop="saddress">
              <el-input v-model="form.saddress" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购票地址" prop="taddress">
              <el-input v-model="form.taddress" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <div class="form-section-title">营业信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业时间" prop="yytime">
              <el-time-select
                v-model="form.yytimeStart"
                :picker-options="{
                  start: '06:00',
                  step: '00:30',
                  end: '23:30'
                }"
                placeholder="开始时间">
              </el-time-select>
              <span style="margin: 0 10px;">至</span>
              <el-time-select
                v-model="form.yytimeEnd"
                :picker-options="{
                  start: '06:00',
                  step: '00:30',
                  end: '23:30'
                }"
                placeholder="结束时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否控制人数" prop="isctrperson">
              <el-select v-model="form.isctrperson" placeholder="请选择">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">

          </el-col>
          <el-col :span="12">
            <el-form-item label="地域" prop="areacode">
              <el-input v-model="form.areacode" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <div class="form-section-title">价格与销量</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="已售出门票数" prop="snums">
              <el-input v-model.number="form.snums" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已下单门票数" prop="onums">
              <el-input v-model.number="form.onums" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-section">
        <div class="form-section-title">其他信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="推荐度" prop="weight">
              <el-input v-model.number="form.weight" autocomplete="off" placeholder="0-100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Web显示" prop="istodayshow">
              <el-select v-model="form.istodayshow" placeholder="请选择">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="景区简介" prop="summary">
          <el-input type="textarea" v-model="form.summary" autocomplete="off" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="景区介绍" prop="sintroduction">
          <el-input type="textarea" v-model="form.sintroduction" autocomplete="off" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="须知" prop="snotice">
          <el-input type="textarea" v-model="form.snotice" autocomplete="off" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="协议" prop="sprotocol">
          <el-input type="textarea" v-model="form.sprotocol" autocomplete="off" :rows="2"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button @click="resetForm('form')">重 置</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,10,15,20,100,200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
  </div>
</div>

<script>
  new Vue({
    el: "#app",
    data() {
      return {
        activeIndex: "1",
        tableData: [], // 列表数据
        currentPage: 1, // 分页参数 第几页
        pageSize: 10, // 分页参数 每页显示的总条数
        total: 0, // 分页参数，列表总条数
        loading: false, // 加载状态
        searchForm: {}, // 搜索表单
        dialogFormVisible: false, // 弹窗显示状态
        title: '添加景区', // 弹窗标题
        form: { // 表单数据
          scenicId: null,
          scenicCode: null,
          scenicName: '',
          scover: '',
          themecode: '',
          seasoncode: '',
          jbcode: '',
          yytimeStart: '',
          yytimeEnd: '',
          yytime: '',
          isctrperson: '0', // 默认值：否
          areacode: '',
          saddress: '',
          taddress: '',
          phone: '',
          summary: '',
          sintroduction: '',
          snotice: '',
          sprotocol: '',
          weight: 0, // 默认值：0
          istodayshow: '0', // 默认值：否
          snums: 0, // 默认值：0
          onums: 0 // 默认值：0
        },

        statusMap: {
          '0': '审核中',
          '1': '审核通过',
          '2': '审核未通过'
        },
        formLabelWidth: '120px',
        rules: { // 表单验证规则
          scenicCode: [
            { required: true, message: '请输入景区代码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) return callback(new Error('请输入景区代码'));
                // 纯数字且长度 2-10
                if (/^\d{2,10}$/.test(value)) {
                  callback();
                } else {
                  callback(new Error('景区代码需为 2-10 位数字'));
                }
              },
              trigger: 'blur'
            }
          ],
          scenicName: [
            { required: true, message: '请输入景区名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          scover: [
            { required: true, message: '请上传或输入封面图片', trigger: 'blur' }
          ],
          themecode: [
            { required: true, message: '请输入主题', trigger: 'blur' }
          ],
          seasoncode: [
            { required: true, message: '请输入时节', trigger: 'blur' }
          ],
          jbcode: [
            { required: true, message: '请输入景区级别', trigger: 'blur' },
            { min: 2, max: 13, message: '长度在 2 到 13 个字符', trigger: 'blur' }
          ],
          yytimeStart: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          yytimeEnd: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ],
          isctrperson: [
            { required: true, message: '请选择是否控制人数', trigger: 'change' }
          ],
          areacode: [
            { required: true, message: '请输入地域', trigger: 'blur' }
          ],
          saddress: [
            { required: true, message: '请输入景区地址', trigger: 'blur' }
          ],
          taddress: [
            { required: true, message: '请输入购票地址', trigger: 'blur' }
          ],
          phone: [
            { required: false, message: '请输入联系电话', trigger: 'blur' }
          ],
          snotice: [
            { required: true, message: '请输入须知', trigger: 'blur' }
          ],
          snums: [
            { required: true, message: '请输入成功售出门票数', trigger: 'blur' },
            { type: 'number', min: 0, message: '请输入非负整数', trigger: 'blur' }
          ],
          onums: [
            { required: true, message: '请输入已下单门票数', trigger: 'blur' },
            { type: 'number', min: 0, message: '请输入非负整数', trigger: 'blur' }
          ],
          weight: [
            { required: true, message: '请输入推荐度', trigger: 'blur' },
            { type: 'number', min: 0, max: 100, message: '请输入0-100的整数', trigger: 'blur' }
          ],
          istodayshow: [
            { required: true, message: '请选择Web显示状态', trigger: 'change' }
          ],

        }
      }
    },
    // 页面加载时执行
    created() {
      this.loadData();
    },
    methods: {
      // 加载列表数据
      loadData() {
        this.loading = true;
        const _this = this;
        axios.post('/scenic/queryByPage', {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: this.searchForm
        })
                .then(response => {
                  if (response.data.code === 200) {
                    _this.tableData = response.data.data.list;
                    _this.total = response.data.data.total;
                  } else {
                    _this.$message.error('数据加载失败：' + (response.data.msg || '未知错误'));
                  }
                })
                .catch(error => {
                  console.error('加载数据出错：', error);
                  _this.$message.error('网络错误，无法加载数据');
                })
                .finally(() => {
                  _this.loading = false;
                });
      },
      // 每页条数改变
      handleSizeChange(val) {
        this.pageSize = val;
        this.loadData();
      },
      // 当前页改变
      handleCurrentChange(val) {
        this.currentPage = val;
        this.loadData();
      },
      // 搜索
      search() {
        this.currentPage = 1;
        this.loadData();
      },
      // 提交表单
      submitForm(formRef) {
        this.$refs[formRef].validate(valid => {
          if (valid) {
            // 合并开始时间和结束时间为一个字符串
            if (this.form.yytimeStart && this.form.yytimeEnd) {
              this.form.yytime = this.form.yytimeStart + '-' + this.form.yytimeEnd;
            } else {
              this.form.yytime = '';
            }
            
            // 修复：添加接口路径（与后端Controller一致）
            const uri = this.title === '更新景区' ? '/scenic/update' : '/scenic/add';
            const _this = this;

            axios.post(uri, this.form)
                    .then(response => {
                      _this.handleResponse(response);
                    })
                    .catch(error => {
                      _this.handleError(error);
                    });
          } else {
            console.log('表单验证失败');
            return false;
          }
        });
      },
      // 响应处理
      handleResponse(response) {
        if (response.data.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.loadData();
          this.dialogFormVisible = false;
        } else {
          this.$message.error('操作失败：' + (response.data.msg || '未知错误'));
        }
      },
      // 错误处理
      handleError(error) {
        console.error('操作出错：', error);
        this.$message.error('网络错误或服务器异常，请稍后重试');
      },
      // 重置表单
      resetForm(formRef) {
        this.$refs[formRef].resetFields();
      },
      // 添加景区
      handleAdd() {
        this.dialogFormVisible = true;
        this.title = '添加景区';
        // 重置表单默认值
        this.form = {
          scenicId: null,
          scenicCode: null,
          scenicName: '',
          scover: '',
          themecode: '',
          seasoncode: '',
          jbcode: '',
          yytimeStart: '',
          yytimeEnd: '',
          yytime: '',
          isctrperson: '0',
          areacode: '',
          saddress: '',
          taddress: '',
          mobile: '',
          phone: '',
          summary: '',
          sintroduction: '',
          snotice: '',
          sprotocol: '',
          weight: 0,
          istodayshow: '0',
          snums: 0,
          onums: 0
        };
      },
      // 编辑景区
      handleEdit(index, row) {
        this.dialogFormVisible = true;
        this.title = '更新景区';
        // 深拷贝避免原数据被修改
        this.form = JSON.parse(JSON.stringify(row));
        
        // 处理营业时间字段，将其拆分为开始和结束时间
        if (this.form.yytime && this.form.yytime.includes('-')) {
          const times = this.form.yytime.split('-');
          this.form.yytimeStart = times[0];
          this.form.yytimeEnd = times[1];
        } else {
          this.form.yytimeStart = '';
          this.form.yytimeEnd = '';
        }
        
        // 确保数字类型字段正确
        this.form.scenicCode = Number(this.form.scenicCode) || null;
        this.form.weight = Number(this.form.weight) || 0;
        this.form.snums = Number(this.form.snums) || 0;
        this.form.onums = Number(this.form.onums) || 0;
      },
      // 删除景区
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该景区信息，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
                .then(() => {
                  const _this = this;
                  axios.delete(`/scenic/deleteById?scenicId=${row.scenicId}`)
                          .then(response => {
                            if (response.data.code === 200) {
                              _this.$message.success('删除成功');
                              _this.loadData();
                            } else {
                              _this.$message.error('删除失败：' + (response.data.msg || '未知错误'));
                            }
                          })
                          .catch(error => {
                            console.error('删除出错：', error);
                            _this.$message.error('网络错误，删除失败');
                          });
                })
                .catch(() => {
                  this.$message.info('已取消删除');
                });
      },
      // 弹窗关闭前回调
      handleDialogClose(done) {
        this.$confirm('确认关闭？未保存的数据将会丢失')
                .then(() => done())
                .catch(() => {});
      },
      // 图片上传成功
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.form.scover = res.data.url;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('图片上传失败：' + (res.msg || '未知错误'));
        }
      },
      // 图片上传失败
      handleAvatarError(err) {
        this.$message.error('图片上传失败：' + (err.message || '网络异常'));
      },
      // 图片上传前校验
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式！');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB！');
        }
        return isJPG && isLt2M;
      }
    }
  });
</script>
</body>
</html>